import React, { PureComponent } from "react";
import { Card, Spin } from 'antd';
import { connect } from "dva";
// import { Link } from "react-router-dom";
// import queryString from 'query-string';
import styles from "./index.less";

import TableList from '../../../components/tablelist/TableList';
import QueryExtra from './components/QueryExtra';
import AdvancedFilter from './components/AdvancedFilter';
import Catalogue from "../../../components/catalogue/Catalogue";
import PageLayout from "../../../components/pageconlayout/PageLayout";
import DealForm from './components/DealForm';

import { openNotificationWithIcon } from '../../../utils/comm';
import { getMenuRouter, getPageOperate } from '../../../components/layouts/menuFn';

@connect(({
  FlowExecution, appListMenu, loading, Public,
}) => ({
  FlowExecutionStore: FlowExecution, loading, menuAppStore: appListMenu,
  focusApp: appListMenu.focusApp,
  menuDataList: Public.menuDataList,
  resourceList: Public.resourceList,
}))
class FlowExecution extends PureComponent {
  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon;
    this.getMenuRouter = getMenuRouter.bind(this);
    this.getPageOperate = getPageOperate.bind(this);
    this.state = {
      page: {
        pageNum: 1,
        pageSize: 6,
      },
      filterVisible: false,
      visible: false,
      selectedKeys: [],
    };
    this.baseQueryParams = {
      appId: '',
      busiId: '',
      searchKey: '',
      timeStart: '', // 开始时间
      timeEnd: '', // 结束时间
    }
    this.queryParams = this.baseQueryParams;
    this.columns = [{
      title: '流程名称',
      dataIndex: 'procDefName',
      key: 'procDefName',
      render: (text, record) => {
        return <a href={`${window.location.origin}${window.routerBase || "/"}flowmanage/flowconfigure/detail?deploymentId=${record.deploymentId}`} target="_blank" rel='noopener noreferrer'>{text}</a>
      },
    }, {
      title: '版本',
      dataIndex: 'version',
      key: 'version',
      width: '12%',
    }, {
      title: '流程编码',
      dataIndex: 'procDefKey',
      key: 'procDefKey',
    }, {
      title: '所属应用',
      dataIndex: 'appName',
      key: 'appName',
    }, {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    }, {
      title: '创建人',
      dataIndex: 'creatorName',
      key: 'creatorName',
      width: '16%',
    }, {
      title: '操作',
      dataIndex: 'opration',
      render: (text, record) => {
        const apply = this.getOprateDisable('apply');
        return (
          <div>
            {apply && (
              <a onClick={(e) => { e.preventDefault(); this.handleDealFormVisible(true, record, false) }}>发起申请</a>
            )}
          </div>
        );
      },
    }];
  }

  componentDidMount() {
    this.isLeaf = false;
    this.initAppListData();
    // this.initData();
  }

  componentDidUpdate(preProps) {
    const { focusApp } = this.props;
    const { focusApp: preFocusApp } = preProps;
    if (preFocusApp.id && `${preFocusApp.id || 0}` !== `${focusApp.id || 0}`) {
      // 应用切换更新页面数据
      this.initAppListData();
      this.resetPageData();
    }
  }

  componentWillUnmount() {
    this.isLeaf = true;
    const { dispatch } = this.props;
    dispatch({ type: "FlowExecution/clearData" });
  }

  // 加载应用数据
  initAppListData = () => {
    const { dispatch } = this.props;
    dispatch({ type: "appListMenu/getAppListData" });
  }

  // 重置页面数据
  resetPageData = () => {
    const { dispatch } = this.props;
    this.queryParams = this.baseQueryParam;
    dispatch({ type: "FlowExecution/clearData" });
    this.setState({ page: { pageNum: 1, pageSize: 6 }, filterVisible: false, selectedKeys: [] });
    if (this.QueryExtra) this.QueryExtra.handleReset();
    if (this.AdvancedFilter) this.AdvancedFilter.handleReset();
  }

  getOprateDisable = (type) => {
    const { location: { pathname = '' }, menuDataList, resourceList } = this.props;
    const res = this.getPageOperate(type, pathname, menuDataList, resourceList);
    return res;
  }

  // 获取查询参数
  getQueryParam = () => {
    const { page: { pageNum, pageSize } } = this.state;
    return { ...this.queryParams, pageNum, pageSize };
  }

  // 获取查询条件组件的this
  getRef = (type, _this) => {
    this[type] = _this;
  }

  // 查询条件改变
  handleParamsChange = (item = {}) => {
    this.queryParams = { ...this.queryParams, ...item }
  }

  // 触发查询
  initData = () => {
    const { dispatch } = this.props;
    const params = this.getQueryParam();
    if (!params.appId && !params.busiId) return;
    dispatch({ type: "FlowExecution/getFlowListData", payload: params });
  }

  // 页码页数改变
  handlePageChange = (pageNum, pageSize) => {
    this.setState({ page: { pageNum, pageSize } }, () => {
      this.initData();
    });
  }

  // 搜索
  handleSearch = () => {
    const { page } = this.state;
    this.setState({ page: { ...page, pageNum: 1 } }, () => {
      this.initData();
    });
  }

  handleTreeNodeSelect = (data, e, preId, nomalSelectedKeys) => {
    const newSelectkeys = nomalSelectedKeys || data;
    const queryParams = { ...this.queryParams };
    if (!(data && data[0].length > 0)) return;
    if (e.node.props.isLeaf) { // 子节点
      this.queryParams = { ...queryParams, busiId: data[0], appId: '' }
    } else {
      this.queryParams = { ...queryParams, appId: data[0], busiId: '' }
    }
    this.setState({ selectedKeys: newSelectkeys });
    this.handleSearch();
  }

  // 部署

  handleDealFormVisible = (visible, record = '',isQuery=false) => {
    this.record = record;
    this.setState({ visible });
    if(isQuery){
      this.handleSearch();
    }
  }

  // Apply = (record = {}) => {
  //   const { procDefKey } = record;
  //   if (!procDefKey) return;
  //   const { dispatch } = this.props;
  //   dispatch({ type: "FlowExecution/processStart", payload: { processDefinitionKey: procDefKey} }).then(({ errCode }) => {
  //     if (errCode === 0) {
  //       this.openNotificationWithIcon('success', '', '申请成功');
  //       this.handleSearch();
  //     }
  //   });
  // }

  handleFilterVisible = () => {
    const { filterVisible } = this.state;
    this.setState({ filterVisible: !filterVisible });
  }

  render() {
    const { FlowExecutionStore, menuAppStore, loading, dispatch } = this.props;
    const { page: { pageNum, pageSize }, filterVisible, visible, selectedKeys } = this.state;
    const { flowListData = [], totalCount = 0 } = FlowExecutionStore;
    const { appListMenuData = [] } = menuAppStore;
    const listLoading = loading.effects['FlowExecution/getFlowListData'] || false;
    const startLoading = loading.effects['FlowExecution/processStart'] || false;
    const menuListLoading = loading.effects['appListMenu/getAppListData'] || false;
    return (
      <div className={styles.root}>
        <PageLayout
          leftContent={
            <Card
              title='应用业务目录'
              style={{ width: '100%', height: '100%', minHeight: window.innerHeight - 64 - 16 - 16 - 104 }}
            >
              <Spin spinning={menuListLoading} delay={300}>
                <Catalogue
                  CatalogueData={appListMenuData}
                  treeNodeSelect={this.handleTreeNodeSelect}
                  selectedKeys={selectedKeys}
                />
              </Spin>
            </Card>
          }
          rightContent={
            <Spin spinning={false} delay={300}>
              <Card
                title={<span className='list__title'>{`流程列表（${totalCount}）`}</span>}
                extra={
                  <QueryExtra
                    onChange={this.handleParamsChange}
                    onSearch={this.handleSearch}
                    visible={filterVisible}
                    handleFilterVisible={this.handleFilterVisible}
                    getRef={(_this) => this.getRef('QueryExtra', _this)}
                  />
                }
                bodyStyle={{ minHeight: window.innerHeight - 64 - 16 - 16 - 48 - 104 }}
                style={{ width: '100%' }}
              >
                <AdvancedFilter
                  handleSearch={this.handleSearch}
                  handleParamsChange={this.handleParamsChange}
                  visible={filterVisible}
                  getRef={(_this) => this.getRef('AdvancedFilter', _this)}
                />
                <TableList
                  dataSource={flowListData}
                  loading={listLoading}
                  columns={this.columns}
                  titleName='procDefName'
                  operationName='opration'
                  onPageChange={this.handlePageChange}
                  rowKey='procDefId'
                  className={styles.listcon}
                  pagination={{
                    showQuickJumper: true,
                    showSizeChanger: true,
                    pageSizeOptions: ['6', '10', '20', '30'],
                    current: pageNum,
                    pageSize,
                    total: totalCount,
                  }}
                />
              </Card>
            </Spin>
          }
        />
        {visible && (
          <DealForm
            visible={visible}
            handleCancel={this.handleDealFormVisible}
            dispatch={dispatch}
            // data={this.record || {}}
            disable={this.disable}
            procDefKey={(this.record || {}).procDefKey || ''}
            confirmLoading={startLoading}
          />
        )}
      </div>
    );
  }
}

export default FlowExecution;